package com.jzweb.zxing.util;

import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import cn.hutool.core.map.MapUtil;

public class QRCodeUtils {

	/**
	 * create qrcode
	 * @param content
	 * @return
	 */
	public static BitMatrix createCode(String content) {
		int width=200, height = 200;
		Map<EncodeHintType, Object> hints = MapUtil.newHashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.MARGIN, 0);
		
		BitMatrix bitMatrix = null;
		try {
			bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitMatrix;
	}
	
	/**
	 * delete while edge
	 * @param matrix
	 * @return
	 */
	public static BitMatrix deleteWhite(BitMatrix matrix) {
		int[] rec = matrix.getEnclosingRectangle();
		int resWidth = rec[2]+1;
		int resHeight = rec[3]+1;
		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
		resMatrix.clear();
		for(int i=0;i<resWidth;i++) {
			for(int j=0;j<resHeight;j++) {
				if(matrix.get(i+rec[0], j+rec[1])) {
					resMatrix.set(i, j);
				}
			}
		}
		return resMatrix;
	}
}
